package com.ruoyi.web.controller.business;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.DtoVehicle;
import com.ruoyi.system.domain.vo.OutGoodsVo;
import com.ruoyi.system.domain.vo.VoVehicle;
import com.ruoyi.system.service.*;
import com.ruoyi.web.controller.websocket.WebSocketUsers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * 车辆预约信息Controller
 * 
 * @author ruoyi
 * @date 2024-04-10
 */
@RestController
@RequestMapping("/business/vehicle")
public class TbVisitorVehicleController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(TbVisitorVehicleController.class);
    @Autowired
    private ITbVisitorVehicleService tbVisitorVehicleService;

    @Autowired
    private ITbDeptService tbDeptService;

    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private ITbFollowerService tbFollowerService;
    @Autowired
    private ITbGoodsService tbGoodsService;
    @Autowired
    private ITbOutGoodService tbOutGoodService;

    @Autowired
    private ITbScreenService tbScreenService;

    @Autowired
    private ITbVehicleHisService tbVehicleHisService;

    @Autowired
    private ITbWhiteListService tbWhiteListService;
    @Autowired
    private ITbVehicleIllegalService tbVehicleIllegalService;

    /**
     * 查询车辆预约信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(DtoVehicle tbVisitorVehicle)
    {
        startPage();
        List<TbVisitorVehicle> list = tbVisitorVehicleService.selectTbVisitorVehicleList(tbVisitorVehicle);

        if (list != null && list.size() > 0) {
            List<VoVehicle> voList = new ArrayList<VoVehicle>();

            for (TbVisitorVehicle item : list) {
                VoVehicle vo = new VoVehicle();
                BeanUtils.copyProperties(item, vo);

                if (StringUtils.isNotBlank(item.getCompanyTo())) {
                    vo.setCompanyToName(DictUtils.getDictLabel("visiting_unit", item.getCompanyTo()));
                }

                if (StringUtils.isNotBlank(item.getVisitingBase())) {
                    vo.setVisitingBaseName(DictUtils.getDictLabel("visiting_base", item.getVisitingBase()));
                }

//                if (StringUtils.isNotBlank(item.getWeighingItems())) {
//                    vo.setWeighingItemsName(dictDataService.selectDictLabel("weighing", item.getWeighingItems()));
//                }

                if (StringUtils.isNotBlank(item.getCommunicationRoom())) {
                    vo.setCommunicationRoomName(dictDataService.selectDictLabel("in_post", item.getCommunicationRoom()));
                }

                if (StringUtils.isNotBlank(item.getVehicleType())) {
                    vo.setVehicleTypeName(dictDataService.selectDictLabel("vehicle_type", item.getVehicleType()));
                }

                String customersType = item.getCustomersType();
                String visitorType = item.getVisitorType();

                vo.setCustomersTypeName(DictUtils.getDictLabel("visitor_vehicle", customersType));
                vo.setVisitorTypeName(DictUtils.getDictLabel(customersType, visitorType));

                if (StringUtils.isNotBlank(item.getIfGoods())) {
                    if ("0".equals(item.getIfGoods())) {
                        vo.setIfWeighingName("否");
                        vo.setGoodsList(new ArrayList<TbGoods>());
                    } else{
                        vo.setIfWeighingName("是");
                        TbGoods gItem = new TbGoods();
                        gItem.setPid(item.getId());
                        List<TbGoods> goods = tbGoodsService.selectTbGoodsList(gItem);
                        if (goods != null && goods.size() > 0) {
                            vo.setGoodsList(goods);
                        } else {
                            vo.setGoodsList(new ArrayList<TbGoods>());
                        }
                    }
                }

                if (StringUtils.isNotBlank(item.getIfFollower())) {
                    if ("0".equals(item.getIfFollower())) {
                        vo.setIfFollowerName("无");
                    } else{
                        vo.setIfFollowerName("有");
                    }
                }

                if (StringUtils.isNotBlank(item.getDriverLicense())) {
                    vo.setDriverLicenseList(item.getDriverLicense().split(","));
                }
                if (StringUtils.isNotBlank(item.getDrivingLicense())) {
                    vo.setDrivingLicenseList(item.getDrivingLicense().split(","));
                }
                
                TbFollower fItem = new TbFollower();
                fItem.setPid(item.getId());
                List<TbFollower> fList = tbFollowerService.selectTbFollowerList(fItem);
                vo.setFollowerList(fList);

                TbOutGood outGoodSearch = new TbOutGood();
                outGoodSearch.setPid(item.getId());
                List<TbOutGood> outGoods = tbOutGoodService.selectTbOutGoodList(outGoodSearch);

                String inList = "";
                String outList = "";
                if (outGoods != null && outGoods.size() > 0) {
                    for (TbOutGood goodItem : outGoods) {

                        if ("0".equals(goodItem.getFlag())) {
                            inList = inList + goodItem.getImage() + ",";
                        }
                        if ("1".equals(goodItem.getFlag())) {
                            outList = outList + goodItem.getImage() + ",";
                        }
                    }
                }

                if (StringUtils.isNotBlank(inList)) {
                    inList = Arrays.stream(inList.split(",")).filter(s -> !s.isEmpty()).reduce((a, b) -> a + "," + b).orElse("");
                }

                if (StringUtils.isNotBlank(outList)) {
                    outList = Arrays.stream(outList.split(",")).filter(s -> !s.isEmpty()).reduce((a, b) -> a + "," + b).orElse("");
                }

                OutGoodsVo outGoodsVo = new OutGoodsVo();
                outGoodsVo.setImgIns(inList);
                outGoodsVo.setImgOuts(outList);
                List<OutGoodsVo> outGoodsVos = new ArrayList<OutGoodsVo>();
                outGoodsVos.add(outGoodsVo);
                vo.setOutGoodsList(outGoodsVos);

                voList.add(vo);
            }
            TableDataInfo rspData = getDataTable(voList);
            rspData.setTotal(tbVisitorVehicleService.selectTbVisitorVehicleCnt(tbVisitorVehicle));
            return rspData;
        }
        return getDataTable(list);
    }

    /**
     * 导出车辆预约信息列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, DtoVehicle tbVisitorVehicle)
    {
        List<TbVisitorVehicle> list = tbVisitorVehicleService.selectTbVisitorVehicleList(tbVisitorVehicle);
        ExcelUtil<TbVisitorVehicle> util = new ExcelUtil<TbVisitorVehicle>(TbVisitorVehicle.class);
        util.exportExcel(response, list, "车辆预约信息数据");
    }

    /**
     * 获取车辆预约信息详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tbVisitorVehicleService.selectTbVisitorVehicleById(id));
    }

    /**
     * 新增车辆预约信息
     */
    @PostMapping
    public AjaxResult add(@RequestBody TbVisitorVehicle tbVisitorVehicle)
    {
        return toAjax(tbVisitorVehicleService.insertTbVisitorVehicle(tbVisitorVehicle));
    }

    /**
     * 修改车辆预约信息
     */
    @PutMapping
    public AjaxResult edit(@RequestBody TbVisitorVehicle dto)
    {
        // 大屏信息
        TbScreen screen = new TbScreen();
        screen.setId(100L);

        LocalDateTime ldt = LocalDateTime.now();
        LocalDateTime todayZero = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 0, 0, 0);
        LocalDateTime todayLasr = LocalDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 23, 59, 59);

        Date dateFrom = Date.from(todayZero.atZone(ZoneId.systemDefault()).toInstant());
        Date dateTo = Date.from(todayLasr.atZone(ZoneId.systemDefault()).toInstant());


        DtoVehicle tbVisitorVehicle = new DtoVehicle();

        tbVisitorVehicle.setInTimeFrom(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateFrom));
        tbVisitorVehicle.setOutTimeTo(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dateTo));

        List<TbVisitorVehicle> countlist = tbVisitorVehicleService.selectTbVisitorVehicleList(tbVisitorVehicle);
        // 今日预约车辆数
        int bookingv = countlist.size();

        TbVisitorVehicle rlt = tbVisitorVehicleService.selectTbVisitorVehicleById(dto.getId());

        TbVehicleHis his = new TbVehicleHis();
        String card = rlt.getCard();
        his.setCard(card); // 车牌号
        his.setInOut("1"); // 入场车辆
        his.setNoteTime(DateUtils.getNowDate());

        if (rlt != null) {

            screen.setPid(rlt.getId());
            // 车牌
            screen.setNumberplate(rlt.getCard());
            // 姓名
            screen.setUserName(rlt.getUserName());
            // 电话
            screen.setTelephone(rlt.getPhone());
            // 来访单位
            screen.setVisiting(rlt.getCompanyFrom());
            // 驾驶证
            screen.setCard(rlt.getDrivingLicense());
            // 车辆类型
            screen.setVehicleType(dictDataService.selectDictLabel("vehicle_type", rlt.getVehicleType()));
            // 进入时间
            screen.setEntry(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getNowDate()));
            screen.setSound("http://ps.jhm.com.cn:8890/prod-api/profile/upload/sound/vist-out.mp3");

            // 过磅物质
            String goodStr = "";
            if (StringUtils.isNotBlank(rlt.getIfWeighing())) {
                if ("0".equals(rlt.getIfWeighing())) {
                    // 是否过磅
                    screen.setWeigh("否");
                } else{
                    // 是否过磅
                    screen.setWeigh("是");
                    // 过磅物资
                    screen.setSupplies(rlt.getWeighingItems());
                    // 物品名称
                    screen.setItemName(rlt.getWeighingItems());
//                    TbGoods gItem = new TbGoods();
//                    gItem.setPid(rlt.getId());
//                    List<TbGoods> goods = tbGoodsService.selectTbGoodsList(gItem);
//                    if (goods != null && goods.size() > 0) {
//                        for (TbGoods goodItem : goods) {
//                            goodStr = goodStr + goodItem.getGoodsName() + ",";
//                        }
//                    }

                    // 查询过磅信息
                    TbWeighbridge weighbridge = tbVisitorVehicleService.selectWeightByVehicleId(rlt.getId());
                    if (weighbridge != null) {
                        screen.setGross(weighbridge.getGross());
                        screen.setTare(weighbridge.getTare());
                        screen.setNet(weighbridge.getNet());

                    } else {
                        screen.setGross("");
                        screen.setTare("");
                        screen.setNet("");
                    }

                    Long allToday = tbVisitorVehicleService.selectAllGrossToday();
                    if (allToday != null) {

                        screen.setGoods(allToday.toString());
                    } else {

                        screen.setGoods("0");
                    }
                }
            }

            // 是否有随行人员
            if (StringUtils.isNotBlank(rlt.getIfFollower())) {
                if ("0".equals(rlt.getIfFollower())) {
                    screen.setPersonnel("无");
                } else{
                    screen.setPersonnel("有");
                }
            }
            // 是否有携带物品
            if (StringUtils.isNotBlank(rlt.getIfGoods())) {
                if ("0".equals(rlt.getIfGoods())) {
                    screen.setBelongings("无");
                } else{
                    screen.setBelongings("有");
                }
            }

            // 来访单位
            // 来访事由
            String customersType = rlt.getCustomersType();
            String visitorType = rlt.getVisitorType();
            String customersNm = DictUtils.getDictLabel("visitor_vehicle", customersType);
            String visitorNm = DictUtils.getDictLabel(customersType, visitorType);

            if (customersNm.equals(visitorNm)) {
                screen.setReason(visitorNm);
            } else {
                screen.setReason(customersNm + "-" + visitorNm);
            }

            String nowDate = DateUtils.getDate();
            TbVehicleIllegal searchIllegal = new TbVehicleIllegal();
            searchIllegal.setOverspeedDate(nowDate);
            searchIllegal.setLicenseNo(rlt.getCard());
            List<TbVehicleIllegal> illegalList = tbVehicleIllegalService.selectTbVehicleIllegalOverspeed(searchIllegal);
            if (illegalList != null && illegalList.size() > 0) {
                String status = illegalList.get(0).getStatus();
                if ("1".equals(status)) {
                    screen.setVehicleStatus("存在超速处罚，QA审批中！");
                } else {
                    screen.setVehicleStatus("存在超速处罚，QA审批未通过！");
                }
            } else {
                screen.setVehicleStatus("允许车辆出厂！");

                rlt.setStatus("5");
                rlt.setDelFlag("2");
                rlt.setUpdateTime(DateUtils.getNowDate());
                rlt.setRemark(dto.getRemark());
                tbVisitorVehicleService.updateTbVisitorVehicle(rlt);
            }

            TbWhiteList whiteSearch = new TbWhiteList();
            whiteSearch.setCard(card);
            List<TbWhiteList> whiteList = tbWhiteListService.selectTbWhiteListList(whiteSearch);
            if (whiteList == null || whiteList.size() == 0) {
                TbVehicleHis hisSearch = new TbVehicleHis();
                hisSearch.setInOut("1");
                hisSearch.setIfVisite("Y");
                hisSearch.setNoteTime(DateUtils.getNowDate());
                hisSearch.setCard(card);

                List<TbVehicleHis> hisList = tbVehicleHisService.checkHisList(hisSearch);
                if (hisList == null || hisList.size() == 0) {
                    his.setIfVisite("Y");
                    his.setInTime(rlt.getInTime());
                    his.setOutTime(rlt.getOutTime());
                    his.setPid(rlt.getId());
                    tbVehicleHisService.insertTbVehicleHis(his);
                }
            }
        } else {

            screen.setPid(0L);
            // 车牌
            screen.setNumberplate(card);
            // 车辆状态
            screen.setVehicleStatus("未预约车辆");
            // 进入时间
            screen.setEntry(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getNowDate()));

            // 姓名
            screen.setUserName("");
            // 电话
            screen.setTelephone("");
            // 驾驶证图片
            screen.setCard("");
            // 车辆类型
            screen.setVehicleType("");
            // 是否过磅
            screen.setWeigh("");
            // 过磅物资
            screen.setSupplies("");
            // 物品名称
            screen.setItemName("");
            // 是否有随行人员
            screen.setPersonnel("");
            // 是否有携带物品
            screen.setBelongings("");
            // 来访单位
            screen.setVisiting("");
            // 来访事由
            screen.setReason("");
            // 毛重
            screen.setGross("");
            // 皮重
            screen.setTare("");
            // 净重
            screen.setNet("");
            // 净重
            screen.setSound("http://ps.jhm.com.cn:8890/prod-api/profile/upload/sound/un-out.mp3");

            TbWhiteList whiteSearch = new TbWhiteList();
            whiteSearch.setCard(card);
            List<TbWhiteList> whiteList = tbWhiteListService.selectTbWhiteListList(whiteSearch);
            if (whiteList == null || whiteList.size() == 0) {
                TbVehicleHis hisSearch = new TbVehicleHis();
                hisSearch.setInOut("1");
                hisSearch.setIfVisite("N");
                hisSearch.setNoteTime(DateUtils.getNowDate());
                hisSearch.setCard(card);

                List<TbVehicleHis> hisList = tbVehicleHisService.checkHisList(hisSearch);
                if (hisList == null || hisList.size() == 0) {
                    his.setIfVisite("N");
                    tbVehicleHisService.insertTbVehicleHis(his);
                }
            }
        }

        // 车辆状态（0默认 1审核中 2审核通过 3审核未通过 4车辆入场 5车辆出场）
        tbVisitorVehicle.setStatus("4");
        tbVisitorVehicle.setCard(null);
        List<TbVisitorVehicle> inlist = tbVisitorVehicleService.selectTbVisitorVehicleList(tbVisitorVehicle);

        // 车辆状态（0默认 1审核中 2审核通过 3审核未通过 4车辆入场 5车辆出场）
        tbVisitorVehicle.setStatus("5");
        List<TbVisitorVehicle> outlist = tbVisitorVehicleService.selectTbVisitorVehicleList(tbVisitorVehicle);

        // 已到车辆
        int vehicles = inlist.size() + outlist.size();

        // 在场车辆
        int vehicling = inlist.size();

        screen.setBookingv(String.valueOf(bookingv));
        screen.setVehicles(String.valueOf(vehicles));
        screen.setVehicling(String.valueOf(vehicling));

        // 已到车辆
        if (vehicles != 0 && bookingv != 0) {
            BigDecimal vp = new BigDecimal(vehicles).divide(new BigDecimal(bookingv), 2, BigDecimal.ROUND_HALF_UP)
                    .multiply(new BigDecimal(100));
            screen.setVehiclesPercentage(vp.toString());
        }

        screen.setUpdateTime(DateUtils.getNowDate());
        tbScreenService.updateTbScreen(screen);
        WebSocketUsers.sendMessageToUsersByText("update");

        return toAjax(1);
    }

    /**
     * 删除车辆预约信息
     */
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tbVisitorVehicleService.deleteTbVisitorVehicleByIds(ids));
    }

    /**
     * 车牌获取车辆信息
     * @param carPlate
     * @return
     */
    @GetMapping(value = "/visitor/{carPlate}")
    //@Log(title = "地磅获取车辆信息", businessType = BusinessType.INSERT)
    public AjaxResult getInfo(@PathVariable("carPlate") String carPlate)
    {
        TbVisitorVehicle item = tbVisitorVehicleService.selectTbVisitorVehicleByPlate(carPlate);
        if (item != null)
        {
            if (StringUtils.isBlank(item.getWeighingItems())) {
                // 未填写过磅物资信息的场合
                return error(carPlate + "未进行过磅预约，请重新预约后再进行过磅");
            }
            String companyTo = item.getCompanyTo();
            item.setCompanyTo(DictUtils.getDictLabel("visiting_unit", companyTo));
        } else {
            return error(carPlate + "未进行过磅预约，请重新预约后再进行过磅");
        }

        return success(item);
    }


    /**
     * 保存地磅信息
     * @param tbWeighbridge
     */
    @PostMapping("/saveWeighbridge")
    //@Log(title = "保存地磅信息", businessType = BusinessType.INSERT)
    public AjaxResult saveWeighbridge(@RequestBody TbWeighbridge tbWeighbridge)
    {
        AjaxResult ar = AjaxResult.error();
        log.info("保存地磅信息入  /saveWeighbridge        TbWeighbridge    {}     "  , JSONObject.toJSONString(tbWeighbridge));
        try {
            ar = tbVisitorVehicleService.saveWeighbridgeInfo(tbWeighbridge);
            log.info("保存地磅信息返回   /saveWeighbridge        TbWeighbridge    {}     "  , JSONObject.toJSONString(ar));
        }catch (Exception e){
            log.error("保存地磅信息错误   /saveWeighbridge        TbWeighbridge    {}     "  , JSONObject.toJSONString(e.getMessage()));
        }
        return ar ;

    }
}
